import { defineStore } from 'pinia';
import { requestIsSuccess } from "@/api/request";
import { warningMessage } from "@/utils/message";
import { DialogType, MapType } from '@/class/map/myMapOpt';
import type { FeatureDataInterface } from '@/class/map/MapData';


export const useEditElementStore = defineStore('EditElement', {
    state: () => ({
        // 编辑或添加的要素
        element: undefined as FeatureDataInterface | undefined, // MarkerData,PolylineData,PolygonData
        fillOpacitySelect: [
            {
                key: 0,
                label: "透明",
                value: "0"
            },
            {
                key: 1,
                label: "半透明",
                value: "0.5"
            },
            {
                key: 2,
                label: "不透明",
                value: "1"
            },
        ],
        // 编辑窗口的可见性
        visible: false,
        // 要素的坐标值和路径
        path: [],
        // 窗口的类型：新增，编辑，新增编辑（编辑 shapefile 读取的数据，并新增）
        dialogType: DialogType.AddData,
        // 窗口现在编辑的要素类型：点线面
        addType: MapType.Marker as MapType
    }),
    actions: {
        setElement(element: FeatureDataInterface) {
            let path = element.getElement().path || element.getElement().position;
            this.addType = element.featureData.type as MapType;
            this.path = path;
            this.element = element as FeatureDataInterface;
        },
        openEdit(dialogType: DialogType) {
            this.dialogType = dialogType;
            this.visible = true;
        },
        closeEdit() {
            this.visible = false;
        },
        setPath(path: []) {
            this.path = path;
        },
        /**
         * 关闭修改窗口，并修改数据
         */
        async saveEditDialog() {
            if (this.element) {
                this.element.setPath(this.path as [])
                if (this.dialogType === DialogType.AddData || this.dialogType === DialogType.EditAndAddData) {
                    let result = await this.element.upload();
                    return true
                } else {
                    let result = await this.element.update();
                    return true
                }
            } else {
                console.error(this)
                warningMessage("编辑数据未设定")
            }
        },
        async deleteEditDialog() {
            if (this.element) {
                let result = await this.element.deleteElement();
                if (requestIsSuccess(result)) {
                    return result;
                } else {
                    warningMessage("删除失败");
                }
            } else {
                console.error(this)
                warningMessage("编辑数据未设定")
            }
        }
    }
});    